﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DatabaseComponent;

public partial class SupportContactsAdminEN : System.Web.UI.Page
{

    public List<HelpDescContacts> lstHelpDescContactsGrid
    {
        get
        {
            if (ViewState["lstHelpDescContactsGrid"] == null)
            {
                ViewState["lstHelpDescContactsGrid"] = System.Guid.NewGuid().ToString();
            }


            if (Session[ViewState["lstHelpDescContactsGrid"].ToString()] == null)
            {
                Session[ViewState["lstHelpDescContactsGrid"].ToString()] = new List<HelpDescContacts>();

            }

            return (List<HelpDescContacts>)Session[ViewState["lstHelpDescContactsGrid"].ToString()];

        }
        set
        {
            if (ViewState["lstHelpDescContactsGrid"] == null)
            {
                ViewState["lstHelpDescContactsGrid"] = System.Guid.NewGuid().ToString();
            }

            Session[ViewState["lstHelpDescContactsGrid"].ToString()] = value;
        }   
   
   

    }




    long mHelpDescContactsID
    {
        get
        {
            if (ViewState["mHelpDescContactsID"] == null)
            {
                ViewState["mHelpDescContactsID"] = System.Guid.NewGuid().ToString();
            }


            if (Session[ViewState["mHelpDescContactsID"].ToString()] == null)
            {
                long obj = -1;
                Session[ViewState["mHelpDescContactsID"].ToString()] = obj;

            }

            return (long)Session[ViewState["mHelpDescContactsID"].ToString()];

        }
        set
        {
            if (ViewState["mHelpDescContactsID"] == null)
            {
                ViewState["mHelpDescContactsID"] = System.Guid.NewGuid().ToString();
            }

            Session[ViewState["mHelpDescContactsID"].ToString()] = value;
        }
    }


    HelpDescContacts mObjHelpDescContacts
    {
        get
        {
            if (ViewState["mObjHelpDescContacts"] == null)
            {
                ViewState["mObjHelpDescContacts"] = System.Guid.NewGuid().ToString();
            }


            if (Session[ViewState["mObjHelpDescContacts"].ToString()] == null)
            {
                Session[ViewState["mObjHelpDescContacts"].ToString()] = new HelpDescContacts();

            }

            return (HelpDescContacts)Session[ViewState["mObjHelpDescContacts"].ToString()];

        }
        set
        {
            if (ViewState["mObjHelpDescContacts"] == null)
            {
                ViewState["mObjHelpDescContacts"] = System.Guid.NewGuid().ToString();
            }

            Session[ViewState["mObjHelpDescContacts"].ToString()] = value;
        }
    }






    protected void Page_Load(object sender, EventArgs e)
    {



        Persons objPersons = GlobalVars.getCurrentPerson();
        checkSecurityAndCustomizePage(objPersons);
       
        if (!Page.IsPostBack)
        {
            bindArea();
            bindGrid(txtSearch.Text);
            editLoad();
        }

        

    }


    /// <summary>
    /// this function will bind all areas
    /// </summary>
    private void bindArea()
    {
        AreaDB objAreaDB = new AreaDB(ConnectionStrings.LMS);
        List<Area> lstArea = objAreaDB.Select("", "");

        lstArea = (from obj in lstArea orderby obj.AreaNameEN select obj).ToList();

        ddlArea.DataSource = lstArea;
        ddlArea.DataTextField = "AreaNameEN";
        ddlArea.DataValueField = "ID";
        ddlArea.DataBind();
    }



    /// <summary>
    /// this function will bind the grid 
    /// </summary>
    protected void bindGrid(string strIn)
    {

        List<HelpDescContacts> lstHelpDescContacts = search(strIn);



        lstHelpDescContactsGrid = lstHelpDescContacts;

        grdUsers.DataSource = lstHelpDescContacts;
        grdUsers.DataBind();
    }



    /// <summary>
    /// it will check the security and customize the page
    /// </summary>
    /// <param name="currentPerson">the person to set security to his previleges</param>
    protected void checkSecurityAndCustomizePage(Persons currentPerson)
    {
        //Security Check

        if (!currentPerson.lstAllRulesIDs.Contains((long)RulesEnum.Page_of_editing_HelpDescContacts))
            Response.Redirect("LoginEN.aspx");


        if (!currentPerson.lstAllRulesIDs.Contains((long)RulesEnum.Editing_Page_of_editing_HelpDescContacts))
        {
            btnSave.Enabled = false;
            btnDelete.Enabled = false;
        }
       




    }
    
    protected void btnSearch_Click(object sender, EventArgs e)
    {

        bindGrid(txtSearch.Text);
       
    }

    /// <summary>
    /// this function will search in Types and return the values
    /// </summary>
    /// <param name="txtText">the text to search for</param>
    /// <returns>a list of types matched</returns>
    protected List<HelpDescContacts> search(string txtText)
    {
        HelpDescContactsDB objHelpDescContactsDB = new HelpDescContactsDB(ConnectionStrings.LMS);
        List<HelpDescContacts> lstRet = new List<HelpDescContacts>();
        if (txtText.Trim() == "")
        {
            List<HelpDescContacts> lstNew = objHelpDescContactsDB.Select(" top 100 ", " order by [NameEN] , [MiddleNameEN] , [LastNameEN] ");
            //lstNew = new List<HelpDescContacts>(from objFol in lstNew where objFol.StatusID != 2 select objFol);
            //no status
            return lstNew;
        }

        string[] strValues = null;
        if (txtText.Trim()[0] == '\"' && txtText.Trim()[txtText.Trim().Length - 1] == '\"')
        {
            try
            {
                strValues = new string[] { txtText.Trim().Substring(1, txtText.Trim().Length - 2) };
                if (strValues[0] == "")
                    strValues = new string[0];
            }
            catch
            {
                strValues = new string[0];
            }
        }
        else
        {
            strValues = txtText.Trim().Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
        }

        foreach (string strValue in strValues)
        {
            HelpDescContacts objHelpDescContacts = new HelpDescContacts();
            objHelpDescContacts.NameAR = objHelpDescContacts.NameEN = objHelpDescContacts.MiddleNameAR = objHelpDescContacts.MiddleNameEN =
            objHelpDescContacts.LastNameAR = objHelpDescContacts.LastNameEN = objHelpDescContacts.Phone1 = objHelpDescContacts.Inner1 =
            objHelpDescContacts.Phone2 = objHelpDescContacts.Inner2 = objHelpDescContacts.Mobile1 = objHelpDescContacts.Mobile2 =
            objHelpDescContacts.Email = "%" + strValue + "%";
            List<HelpDescContacts> lstHelpDescContacts = objHelpDescContactsDB.SearchOrLike(objHelpDescContacts);
            //lstHelpDescContacts = new List<HelpDescContacts>(from objFol in lstHelpDescContacts where objFol.StatusID != 2 select objFol);
            //no status
            foreach (HelpDescContacts objFol in lstHelpDescContacts)
            {
                if ((from objIn in lstRet where objIn.ID == objFol.ID select objIn).Count() == 0)
                {
                    lstRet.Add(objFol);
                }
            }

        }

        lstRet = (from obj in lstRet orderby obj.NameEN, obj.MiddleNameEN, obj.LastNameEN select obj).ToList();
        return lstRet;



    }





    protected void grdUsers_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {

        Persons objCurrentPersons = GlobalVars.getCurrentPerson();
        checkSecurityAndCustomizePage(objCurrentPersons);

        //security check

        if (!objCurrentPersons.lstAllRulesIDs.Contains((long)RulesEnum.Editing_Page_of_editing_HelpDescContacts))
        {
            lblError.Text = "Security error , you can view only";
            lblResult.Text = "";

            return;
        }


        long HelpDescContactsID = long.Parse(grdUsers.DataKeys[e.RowIndex]["ID"].ToString());



        HelpDescContactsDB objHelpDescContactsDB = new HelpDescContactsDB(ConnectionStrings.LMS);
        List<HelpDescContacts> lstHelpDescContacts = objHelpDescContactsDB.getHelpDescContactsByID(HelpDescContactsID);




        if (lstHelpDescContacts.Count == 0)
        {
            lblError.Text = "No Contacts to delete";
            lblResult.Text = "";
            return;
        }





       


        objHelpDescContactsDB.Delete(lstHelpDescContacts[0]);



        lblResult.Text = "Deleted ok.";



        bindGrid(txtSearch.Text);



    }

    protected void btnNew_Click(object sender, EventArgs e)
    {
        clearAllControls();
    }
    protected void grdUsers_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        grdUsers.DataSource = lstHelpDescContactsGrid;
        grdUsers.PageIndex = e.NewPageIndex;

        grdUsers.DataBind(); 
    }


    /// <summary>
    /// this function will check mHelpDescContactsID to detect update or insert
    /// </summary>
    protected void checkID()
    {
        if (mHelpDescContactsID != -1)
        {
            try
            {

                HelpDescContactsDB objHelpDescContactsDB = new HelpDescContactsDB(ConnectionStrings.LMS);
                List<HelpDescContacts> lstHelpDescContacts = objHelpDescContactsDB.getHelpDescContactsByID(mHelpDescContactsID);
                if (lstHelpDescContacts.Count > 0)
                {


                    mObjHelpDescContacts = lstHelpDescContacts[0];
                    btnDelete.Visible = true;

                }
                else
                {
                    mHelpDescContactsID = ((long)-1);
                    btnDelete.Visible = false;
                    
                }


            }
            catch
            {
                mHelpDescContactsID = ((long)-1);
                btnDelete.Visible = false;
            }


            
        }
        else
        {
            btnDelete.Visible = false;

        }
    }



    /// <summary>
    /// this will bind the Ticket Types to update or delete
    /// </summary>
    protected void BindAllControls()
    {
        if (mHelpDescContactsID != -1)
        {


            txtNameAR.Text = mObjHelpDescContacts.NameAR;
            txtNameEN.Text = mObjHelpDescContacts.NameEN;
            txtMiddleNameAR.Text = mObjHelpDescContacts.MiddleNameAR;
            txtMiddleNameEN.Text = mObjHelpDescContacts.MiddleNameEN;
            txtLastNameAR.Text = mObjHelpDescContacts.LastNameAR;
            txtLastNameEN.Text = mObjHelpDescContacts.LastNameEN;
            txtPhone1.Text = mObjHelpDescContacts.Phone1;
            txtInner1.Text = mObjHelpDescContacts.Inner1;
            txtPhone2.Text = mObjHelpDescContacts.Phone2;
            txtInner2.Text = mObjHelpDescContacts.Inner2;
            txtMobile1.Text = mObjHelpDescContacts.Mobile1;
            txtMobile2.Text = mObjHelpDescContacts.Mobile2;
            txtEmail.Text = mObjHelpDescContacts.Email;
            ddlArea.SelectedValue = mObjHelpDescContacts.AreaID.ToString();

            

        }
    }



    /// <summary>
    /// this function will read all controls values
    /// </summary>
    protected void ReadAllControls()
    {

        if (mObjHelpDescContacts == null)
            mObjHelpDescContacts = new HelpDescContacts();


        mObjHelpDescContacts.NameAR = txtNameAR.Text;
        mObjHelpDescContacts.NameEN = txtNameEN.Text == "" ? txtNameAR.Text : txtNameEN.Text;
        mObjHelpDescContacts.MiddleNameAR = txtMiddleNameAR.Text;
        mObjHelpDescContacts.MiddleNameEN = txtMiddleNameEN.Text;
        mObjHelpDescContacts.LastNameAR = txtLastNameAR.Text;
        mObjHelpDescContacts.LastNameEN = txtLastNameEN.Text == "" ? txtLastNameAR.Text : txtLastNameEN.Text;

        mObjHelpDescContacts.Phone1 = txtPhone1.Text;
        mObjHelpDescContacts.Inner1 = txtInner1.Text;
        mObjHelpDescContacts.Phone2 = txtPhone2.Text;
        mObjHelpDescContacts.Inner2 = txtInner2.Text;

        mObjHelpDescContacts.Mobile1 = txtMobile1.Text;
        mObjHelpDescContacts.Mobile2 = txtMobile2.Text;

        mObjHelpDescContacts.Email = txtEmail.Text;

        mObjHelpDescContacts.AreaID = long.Parse(ddlArea.SelectedValue);




    }



    /// <summary>
    /// this function for clearing controls
    /// </summary>
    protected void clearAllControls()
    {

        txtNameAR.Text = "";
        txtNameEN.Text = "";
        txtMiddleNameAR.Text = "";
        txtMiddleNameEN.Text = "";
        txtLastNameAR.Text = "";
        txtLastNameEN.Text = "";
        txtPhone1.Text = "";
        txtInner1.Text = "";
        txtPhone2.Text = "";
        txtInner2.Text = "";
        txtMobile1.Text = "";
        txtMobile2.Text = "";
        txtEmail.Text = "";
        

        mObjHelpDescContacts = new HelpDescContacts();

        mHelpDescContactsID = -1;

    }



    /// <summary>
    /// this function for loading the editing behavior
    /// </summary>
    protected void editLoad()
    {


        Persons currentPerson = GlobalVars.getCurrentPerson();




       

            checkSecurityAndCustomizePage(currentPerson);

            checkID();


            BindAllControls();




        
    }



    /// <summary>
    /// this function will Save the Ticket type
    /// </summary>
    protected void Save()
    {


        if (checkForRepeats())
        {
            HelpDescContactsDB objHelpDescContactsDB = new HelpDescContactsDB(ConnectionStrings.LMS);
            if (mObjHelpDescContacts.ID == -1)
            {
                objHelpDescContactsDB.Insert(mObjHelpDescContacts);
                clearAllControls();
                bindGrid(txtSearch.Text);
                lblResult.Text = "Data saved ok.";
            }
            else
            {
                objHelpDescContactsDB.Update(mObjHelpDescContacts);
                bindGrid(txtSearch.Text);
                BindAllControls();
                lblResult.Text = "Data saved ok.";

            }



        }


    }


    /// <summary>
    /// this function will check if the Ticket type exist with the same Name or not
    /// </summary>
    /// <returns>true if ok , false for error (Ticket type exist before)</returns>
    protected bool checkForRepeats()
    {
        HelpDescContactsDB objHelpDescContactsDB = new HelpDescContactsDB(ConnectionStrings.LMS);

        HelpDescContacts objSearch = new HelpDescContacts();
        objSearch.NameAR = mObjHelpDescContacts.NameAR;
        objSearch.LastNameAR = mObjHelpDescContacts.LastNameAR;
        objSearch.AreaID = mObjHelpDescContacts.AreaID;
        objSearch.MiddleNameAR = mObjHelpDescContacts.MiddleNameAR;

        List<HelpDescContacts> lstOldHelpDescContacts = objHelpDescContactsDB.Search(objSearch);

        List<HelpDescContacts> lstExist = lstOldHelpDescContacts;

        if (lstExist.Count > 0)
        {

            errorExist();
            return false;
        }


       





        return true;

    }




    /// <summary>
    /// this function will show a message with the error for existense
    /// </summary>
    private void errorExist()
    {

        lblError.Text = "Error , a contact with the same name ,middle name, lastname and area  is already found , choose a new Name";

    }



    protected void btnSave_Click(object sender, EventArgs e)
    {

        //security check
        Persons currentPerson = GlobalVars.getCurrentPerson();
        if (!currentPerson.lstAllRulesIDs.Contains((long)RulesEnum.Editing_Page_of_editing_HelpDescContacts))
            return;


        if (Page.IsValid)
        {



            ReadAllControls();






            Save();


        }
    }




    protected void btnDelete_Click(object sender, EventArgs e)
    {

        //security check
        Persons currentPerson = GlobalVars.getCurrentPerson();
        if (!currentPerson.lstAllRulesIDs.Contains((long)RulesEnum.Editing_Page_of_editing_HelpDescContacts))
            return;


        ReadAllControls();


        long HelpDescContactsID = mHelpDescContactsID;




        HelpDescContactsDB objHelpDescContactsDB = new HelpDescContactsDB(ConnectionStrings.LMS);
        List<HelpDescContacts> lstHelpDescContacts = objHelpDescContactsDB.getHelpDescContactsByID(HelpDescContactsID);




        if (lstHelpDescContacts.Count == 0)
        {
            lblError.Text = "No Contacts to delete";
            lblResult.Text = "";
            return;
        }





        


        objHelpDescContactsDB.Delete(lstHelpDescContacts[0]);


        bindGrid(txtSearch.Text);
        lblResult.Text = "Deleted ok.";



        

        clearAllControls();






    }


    /// <summary>
    /// this function to get arabic full name if not found it will get the english one
    /// </summary>
    /// <param name="obj">the Container.DataItem from grid which is a HelpDescContacts object</param>
    /// <returns>the full name of the contact</returns>
    protected string getFullName(object obj)
    {
        HelpDescContacts objDescContacts = (HelpDescContacts)obj;

        if (objDescContacts.FullNameEN != "")
            return objDescContacts.FullNameEN;
        else
            return objDescContacts.FullNameAR;

        

    }


    /// <summary>
    /// this function will return area name of the contact area
    /// </summary>
    /// <param name="objDataItem">the object that have the helpdescContact</param>
    /// <returns>a string containing area name</returns>
    protected string getAreaName(object objDataItem)
    {
        HelpDescContacts obj = (HelpDescContacts)objDataItem;

        return obj.objArea.AreaNameEN;
    }



    protected void grdUsers_RowEditing(object sender, GridViewEditEventArgs e)
    {
        Persons objCurrentPersons = GlobalVars.getCurrentPerson();
        checkSecurityAndCustomizePage(objCurrentPersons);

        

        long HelpDescContactsID = long.Parse(grdUsers.DataKeys[e.NewEditIndex]["ID"].ToString());

        mHelpDescContactsID = HelpDescContactsID;

        editLoad();

        e.Cancel = true;

    }
}
